<?php
App::uses('AppController', 'Controller');
/**
 * Users Controller
 *
 * @property User $User
 * @property PaginatorComponent $Paginator
 * @property nComponent $n
 */
class UsersController extends AppController {

	public $prefix_layout = true;
    public $allow = array('register','login','register','forget_password');
    public $uses = array('User');
   	public $layout = 'user';


    public function register($action='/Users/home') {
        $this->layout = '';
        $this->site_title = '快速注册 ';

        if ( $this->UserAuth->isLogged() ) {
            $uri = $this->Session->read( UserAuthComponent::originAfterLogin );
            $this->Session->delete( UserAuthComponent::originAfterLogin );
            if ( $uri )
                $this->redirect( $uri );
            else
                $this->redirect($action);
        }

        if ( $this->request->isPost() ) {
            $postData = $this->data;
            $postData['User']['role'] = 'user';
            $postData['User']['created'] = time();
            $postData['User']['last_login'] = time();

            if ( @$postData['User']['password'] !== @$postData['User']['cpassword'] ) {
                $this->User->validationErrors = array(
                    'cpassword' => array( '两次输入密码不一致' )
                );
                return;
            }
            $this->User->create( $postData );
            if ( $this->User->RegisterValidate() ) {
                $user = $this->User->save( $postData );
                
                //创建账户
                $this->loadModel('Account');
                $this->Account->create();
                $this->Account->save( array( 'user_id' => $user['User']['id'] ) );

                $this->UserAuth->flashUser( $user['User']['id'] );

                $this->User->sendRegistrationMail( $user );

                $uri = $this->Session->read( UserAuthComponent::originAfterLogin );
                $this->Session->delete( UserAuthComponent::originAfterLogin );
                if ( $uri )
                    $this->redirect( $uri );
                else
                    $this->redirect( $action );
            }
        }
    }

    public  function login( $action = '/Users/home' ) {
        $this->layout = '';
        if ( $this->request->isPost() ) {

            $this->request->data['User']['email'] = trim( $this->request->data['User']['email'] );
            $this->request->data['User']['password'] = trim( $this->request->data['User']['password'] );

            $postData = $this->data;

            $email = $postData['User']['email'];
            $password = $postData['User']['password'];
            $this->User->recursive = -1;
            $this->User->cache=false;
            $user = $this->User->findByEmail( $email );
            if (!$user) {
                $user = $this->User->findByEmail( $email );
                if ( empty( $user ) ) {
                    $this->User->validationErrors = array(
                        'email' => array( "用户不存在" )
                    );
                    $this->error( '用户不存在' );
                    return;
                }
            }

            if ( $user['User']['password'] === $password) {
                $this->UserAuth->login( $user );
                $uri = $this->Session->read(UserAuthComponent::originAfterLogin );
                if ( !$uri) {
                    $uri = $action;
                }
                CakeSession::delete( 'Message.flash' );
                $this->Session->delete( UserAuthComponent::originAfterLogin );
                $this->redirect( $uri );
            }
            $this->User->validationErrors = array(
                'password' => array( "密码错误" )
            );
            $this->error( '密码错误' );
            return;
        }
    }

    public function logout() {
        $this->layout = 'user';
        $this->UserAuth->logout();

        $this->Session->delete( UserAuthComponent::originAfterLogin );

        $this->redirect( array( 'action' => 'login' ) );
    }

    public function home()
    {
    	$this->layout = 'user';
    }

    public function forget_password()
    {
        $this->layout = '';
    }

    /**
     * 修改密码
     */
    public function password()
    {
        $user = $this->UserAuth->getUser();

        if ($this->request->isPost() || $this->request->isPut()) {
            $post_data = $this->request->data['User'];
            if($user['User']['password'] != $post_data['password']){
                $this->User->validationErrors['password'] = "旧的密码错误";
                return ;
            }
            if($post_data['newpassword'] != $post_data['cpassword']){
                $this->User->validationErrors['cpassword'] = "两次输入密码不一致";
                return ;
            }
            if(strlen($post_data['newpassword']) < 6){
                $this->User->validationErrors['newpassword'] = "最低输入6位";
                return ;
            }
            $this->User->id = $user['User']['id'];
            if($this->User->saveField('password',$post_data['newpassword'])){
                $this->succ('修改成功!');
                $this->redirect(array('action'=>'home'));
            }else{
                $this->error("修改失败");
            }
        }

    }

    /**
     * 修改支付密码
     */
    public function pay_password()
    {
        $user = $this->UserAuth->getUser();
        
        if ($this->request->isPost() || $this->request->isPut()) {
            $post_data = $this->request->data['User'];
            if($user['User']['paypassword'] != $post_data['pay_password']){
                $this->User->validationErrors['paypassword'] = "旧的密码错误";
                return ;
            }
            if($post_data['newpaypassword'] != $post_data['cpassword']){
                $this->User->validationErrors['cpassword'] = "两次输入密码不一致";
                return ;
            }
            if(strlen($post_data['newpaypassword']) < 6){
                $this->User->validationErrors['newpaypassword'] = "最低输入6位";
                return ;
            }
            $this->User->id = $user['User']['id'];
            if($this->User->saveField('pay_password',$post_data['newpaypassword'])){
                $this->succ('修改成功!');
                $this->redirect(array('action'=>'home'));
            }else{
                $this->error("修改失败");
            }
        }

    }
/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->User->recursive = 0;
		$this->set('users', $this->Paginator->paginate());
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
		$this->set('user', $this->User->find('first', $options));
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
			$this->User->create();
			if ($this->User->save($this->request->data)) {
				return $this->flash(__('The user has been saved.'), array('action' => 'index'));
			}
		}
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->User->save($this->request->data)) {
				return $this->flash(__('The user has been saved.'), array('action' => 'index'));
			}
		} else {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$this->request->data = $this->User->find('first', $options);
		}
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->User->delete()) {
			return $this->flash(__('The user has been deleted.'), array('action' => 'index'));
		} else {
			return $this->flash(__('The user could not be deleted. Please, try again.'), array('action' => 'index'));
		}
	}

/**
 * admin_index method
 *
 * @return void
 */
	public function admin_index() {
		$this->User->recursive = 0;
        $this->paginate = array(
            'order'=>'User.id desc'
        );
		$this->set('data', $this->paginate());
	}


/**
 * admin_add method
 *
 * @return void
 */
	public function admin_add() {
		if ($this->request->is('post')) {
			$this->User->create();
			if ($this->User->save($this->request->data)) {
				return $this->flash(__('The user has been saved.'), array('action' => 'index'));
			}
		}
	}

	public function admin_edit($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('无效用户!'));
		}
		if ($this->request->is(array('post', 'put'))) {
            $post_data = $this->request->data;
			if ($this->User->save($post_data)) {
			     $this->succ('修改成功!');
			     $this->redirect($this->referer());
            }else{
                $this->error('修改失败');
            }
		} else {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$this->request->data = $this->User->find('first', $options);
		}
	}

/**
 * admin_delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_delete($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->User->delete()) {
			return $this->flash(__('The user has been deleted.'), array('action' => 'index'));
		} else {
			return $this->flash(__('The user could not be deleted. Please, try again.'), array('action' => 'index'));
		}
	}}
